/**
 * Created by Administrator on 2017/7/31.
 */


$(document).ready(function () {
    var id=locationSearcher('productId');
    //当sku数量为1时，获取当前数量为1的skuid、
    var oneSkuId='',buyId='';

    //商品详情模板编译
    var detailTpl=$('#detail-template').html();
    var detailCmp=Handlebars.compile(detailTpl);

    //商品类型模板编译
    var goodsTypeTpl=$('#goods-type-template').html();
    var goodsTypeCmp=Handlebars.compile(goodsTypeTpl);

    //商品详情模板编译
    var a = $('#goodsdetail-con-detail').html();
    var b = Handlebars.compile(a);

    //ajax获取数据
    $.ajax({
        url:C.interface.detail,
        dataType:'json',
        data:{
            productId:id
        },
        success:function (response) {
            if (response.result=='success'){
                console.log(response.data);
                var data=response.data;
                //console.log(data.product.detailImageUrls);
                $('#detail-box').html(detailCmp(data));
                $('#goods-type').html(goodsTypeCmp(data));
                $('.goodsdetail-con-detail').html(b(data));
                //轮播图
                var slide = new auiSlide({
                    container:document.getElementById("aui-slide"),
                    // "width":300,
                    //"height":$(this).width,
                    "speed":500,
                    "autoPlay": 3000, //自动播放
                    "loop":false,
                    "pageShow":true,
                    "pageStyle":'dot',
                    'dotPosition':'center'
                });

                //轮播图大小
                var imgWidth=$('.bg-dark').width();
                console.log(imgWidth);
                $('.aui-slide-wrap').css('height',imgWidth);
                $('.bg-dark').find('img').css('height',imgWidth);


                //当sku款式为1时，移除该显示，否则显示款式
                var count=data.skus.length;
                console.log(count);
                var typeList=$('.goods-type-list');
                if (typeList.length>1){
                    typeList.eq(0).addClass('goods-type-active');
                    typeList.bind('click',function () {
                        $(this).addClass('goods-type-active').siblings().removeClass('goods-type-active');
                        var origin=$(this).data('origin');
                        var price=$(this).data('price');
                        $('.current-price').html(price);
                        $('.origin-price').html(origin);

                    });
                }else {
                    oneSkuId=$('.goods-type-list').data('skuid');
                    $('#goods-type').remove();
                }

                //控制款式的显示与隐藏
                $('.select-box').click(function () {
                    var arrowUp=$(this).find('.select-arrow').attr('src');
                    var arrowDefault='../img/arrow_u.png';
                    if (arrowUp == arrowDefault){
                        $(this).find('.select-arrow').attr('src','../img/arrow_d.png');
                        $('.select-style-show').show(200);
                    }else {
                        $(this).find('.select-arrow').attr('src','../img/arrow_u.png');
                        $('.select-style-show').hide(200);
                    }

                });

                //商品分享
                $('.product-share').bind('click',function (event) {
                    event.preventDefault();
                    $('.mask').show();
                    $('.share-section').show();
                });

                $('.close-share').find('img').click(function () {
                    $('.mask').hide();
                    $('.share-section').hide();
                });

                $('.share').click(function () {
                    var status=$(this).data('status');
                    var url=window.location.href;
                    var content=$('.this-shop-name').html();
                    var shareData={
                        postType:'shareProduct',
                        status:status,
                        url:C.share+'?productId='+id,
                        title:'友惠家商城',
                        content:content
                    };

                    console.log(shareData);

                    var ua = navigator.userAgent.toLowerCase();
                    if (/iphone|ipad|ipod/.test(ua)) {
                        iosShareProduct(shareData);
                    } else {
                        androidShareProduct(JSON.stringify(shareData));
                    }
                });

                //加入购物车
                $('.join-cart').bind('click',joinCart);

                /*$('.join-cart').bind('click',function () {
                    /!**
                     * 本地存储当前选中的商品加入购物车
                     * *!/

                     var skuId=null;
                     var typeList=$('.goods-type-list');

                     if (typeList.length>1){
                     skuId=$('.goods-type-active').data('skuid');
                     }else {
                     skuId=oneSkuId;
                     }

                    var productId=$('.aui-slide-wrap').data('productid');

                    var redPrice=$('.red-price').html();
                    var thisShopName=$('.this-shop-name').html();
                    var currentPrice=$('.current-price').html();
                    var originPrice=$('.origin-price').html();
                    var baoyou=$('.detail-buy').find('span').eq(0).html();
                    var thisImg=$('.aui-slide-wrap').data('thisimg');
                    var storage=new Storage('shoppingCard');
                    var shopCart=storage.get('shoppingCard');
                    //本地存储的数据
                    var localData={
                        redPrice:redPrice,
                        thisShopName:thisShopName,
                        thisImg:thisImg,
                        currentPrice:currentPrice,
                        originPrice:originPrice,
                        baoyou:baoyou,
                        skuId:skuId,
                        productId:productId
                    };
                    if (shopCart.length==0||shopCart==null){
                        showDefault('success');
                        storage.add(localData);
                    }else {
                        var flag=0;
                        for(var i=0;i<shopCart.length;i++){
                            console.log(shopCart[i].skuId);
                            if (shopCart[i].skuId==skuId){
                                flag=1;
                            }
                        }
                        if (flag==1){
                            showDefault('success');
                        }else {
                            showDefault('success');
                            storage.add(localData);
                        }
                    }





                });*/
                
                $('#now-pay').click(function () {

                    var productId=$('.aui-slide-wrap').data('productid');
                    var skuId=null;
                    var typeList=$('.goods-type-list');

                    if (typeList.length>1){
                        skuId=$('.goods-type-active').data('skuid');
                    }else {
                        skuId=oneSkuId;
                    }

                    buyId=productId+':'+skuId+':'+1+',';
                    //console.log(buyId);
                    //alert(buyId);
                    localStorage.setItem('orderSubmitId',buyId);
                    var orderSubmitId=localStorage.getItem('orderSubmitId');
                    console.log(orderSubmitId);
                    location.href='now_buy.html?version='+C.version;
                })
            }else if (response.result === 'login'){
                alert('登录过期请重新登录');
                againLogin();
            }else {
                alert(response.errorMsg);
            }
        }
    });



    function joinCart() {
        var loading =dialog.loading();

        var skuId=null;
        var typeList=$('.goods-type-list');

        if (typeList.length>1){
            skuId=$('.goods-type-active').data('skuid');
        }else {
            skuId=oneSkuId;
        }

        $.ajax({
            url:C.interface.addCart,
            type:'get',
            dataType:'json',
            data:{
                token:C.token,
                productSkuId:skuId
            },
            complete:function () {
                loading.close();
            },
            success:function (response) {
                if (response.result === 'success'){
                    dialog.tusiSuccess('加入购物车成功！');
                }
            }
        })
    }



    /*跳转购物车页面*/
    $('.go-cart').bind('click',function () {
        window.location.href='cart.html';
    });


    /*dialog 弹出层*/
    var toast = new auiToast({
    });
    function showDefault(type){
        switch (type) {
            case "success":
                toast.success({
                    title:"加入购物车成功",
                    duration:2000
                });
                break;
            case "fail":
                toast.fail({
                    title:"加入购物车失败",
                    duration:2000
                });
                break;
        }
    }

    /**
     * 利用本地存储实现购物车
     * cartLocal
     * */
    function Storage(key) {
        //添加一项数据
        //value:object
        this.add=function (value) {
            if (value){
                var v=this.get();
                v.push(value);
                this.set(v);
            }
        };
        //设置数据
        //value：array null
        this.set=function (value) {
            if (value){
                var v=JSON.stringify(value);
                localStorage.setItem(key,v);
            }else {
                localStorage.removeItem(key);
            }
        };
        // 获取数据
        this.get=function () {
            var value=localStorage.getItem(key)||'[]';
            return JSON.parse(value);
        }
    }


    //调用iOS分享方法
    function iosShareProduct(param) {
        window.webkit.messageHandlers.shareProduct.postMessage(param);
    }

    //调用Android分享
    function androidShareProduct(param) {
        window.huifa.shareProduct(param);
    }





});

